package com.opd.soeghtool;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.constraint.ConstraintLayout;
import android.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsoluteLayout;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainService extends Service {

    private static final String TAG = "SOEService";
    private final boolean ENABLE_HALF_HIDE = false;

    private int mImageHalfSize = 20;
    GlobalVar mGlobalVar;
    private boolean bHalfshow = false;
    private boolean bleftside = true;
    private boolean bmenuView = false;
    private boolean bfloatView = false;
    private boolean bCenterMode = false;
    ConstraintLayout toucherLayout;
    LinearLayout toucherLayout1,alertDialog;
    AbsoluteLayout floatLayout;
    WindowManager.LayoutParams params,params1,params2;
    WindowManager windowManager;


    ImageView iv_btn[];
    int ImgIDTbl[] ={R.id.iv_btn_a,R.id.iv_btn_b,R.id.iv_btn_x,R.id.iv_btn_y,R.id.iv_btn_up,R.id.iv_btn_down,
            R.id.iv_btn_left,R.id.iv_btn_right,R.id.iv_btn_l1,R.id.iv_btn_r1,R.id.iv_btn_l2,R.id.iv_btn_r2,
            R.id.iv_btn_back,R.id.iv_btn_turbo,
            R.id.iv_btn_start,R.id.iv_btn_select,R.id.iv_left_rocker,R.id.iv_right_rocker,
    };
    int Img[] ={R.drawable.btn_a,R.drawable.btn_b,R.drawable.btn_x,R.drawable.btn_y,R.drawable.btn_up,R.drawable.btn_down,R.drawable.btn_left,R.drawable.btn_right,
            R.drawable.l1,R.drawable.r1,R.drawable.l2,R.drawable.r2,R.drawable.btn_s2,R.drawable.btn_s1,R.drawable.btn_s4,R.drawable.btn_s3};
    Button btn_img_pos_reset,btn_img_pos_save,btn_img_pos_exit,btn_img_pos_hide;

    ListView lv_btnlist;
    FuncAdapter funcAdapter;
    ArrayList<Map<String, Object>> listData;

    private int mSize = 150;
    private int qv_ly_width = 500,qv_ly_height = 500;
    //状态栏高度.
    int statusBarHeight = 0;
    int orientationStatus;
    private int screenWidth= 1080;//Resources.getSystem().getDisplayMetrics().widthPixels;
    private int screenHeight = 1920;//Resources.getSystem().getDisplayMetrics().heightPixels;
    private static Handler handler;
    private Message message;

    private int pttbl_temp[];
    boolean bIsChanged = false;
    byte u8DataBuffer[];
    byte g_u8tAttrTable[][];


    MyBroadcastReceive broadcastReceive;
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.i(TAG,"MainService Created");
        Configuration mConfiguration = this.getResources().getConfiguration(); //获取设置的配置信息
        orientationStatus = mConfiguration.orientation; //获取屏幕方向
        Log.i(TAG, "orientationStatus:" + orientationStatus);
        mGlobalVar = (GlobalVar)getApplication();
        pttbl_temp = new int[mGlobalVar.getDeviceMaxButton()*2];
        u8DataBuffer = new byte[Transfer_Con.HID_PACKET_SIZE];
        g_u8tAttrTable = new byte[mGlobalVar.getDeviceMaxButton()][3];
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        display.getRealMetrics(dm);
        screenHeight = dm.widthPixels;
        screenWidth = dm.heightPixels;

        if(mGlobalVar.getIsPortraitGame())
        {
            bCenterMode = true;
            if (screenWidth < screenHeight)
            {
                int a = screenWidth;
                screenWidth = screenHeight;
                screenHeight = a;
                Log.d(TAG, "Swap to Portrait Mode");
            }
        }
        else
        {
            if (screenWidth > screenHeight) {
                int a = screenWidth;
                screenWidth = screenHeight;
                screenHeight = a;
                Log.d(TAG, "swap to Landscape Mode");
            }
        }
        Log.d(TAG,"wid:"+String.valueOf(screenWidth)+" Hei:"+String.valueOf(screenHeight));

        mSize = dip2px(this,30);
        qv_ly_width = dip2px(this,110);;
        qv_ly_height = dip2px(this,150);;


        createToucher();
        broadcastReceive = new MyBroadcastReceive();
//注册广播接收,注意：要监听这个系统广播就必须用这种方式来注册，不能再xml中注册，否则不能生效
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.CONFIGURATION_CHANGED");
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(broadcastReceive,filter);
    }

    @SuppressLint({"ClickableViewAccessibility", "HandlerLeak"})
    private void createToucher() {

        Log.d(TAG,"createToucher()");
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(ENABLE_HALF_HIDE) {
                    Log.i(TAG, "Handler:scrollBy");
                    if (bleftside) {
                        toucherLayout.scrollBy(mSize / 2, 0);
                        params.x = params.x - 100;
                    } else {
                        toucherLayout.scrollBy(-mSize / 2, 0);
                        params.x = params.x + 100;
                    }
                    //params.width = 50;

                    Log.d(TAG, "x :" + params.x);
                    Log.d(TAG, "y :" + params.y);
                    windowManager.updateViewLayout(toucherLayout, params);
                    bHalfshow = true;
                }
                if(!mGlobalVar.getFloatMode()) {
                    if (bmenuView && (toucherLayout1 != null)) {
                        windowManager.removeView(toucherLayout1);
                        bmenuView = false;
                    }
                }
            }
        };
        message = handler.obtainMessage();
        message.what = 0;
        //赋值WindowManager&LayoutParam.
        params = new WindowManager.LayoutParams();
        params1 = new WindowManager.LayoutParams();
        params2 = new WindowManager.LayoutParams();
        windowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
        //设置type.系统提示型窗口，一般都在应用程序窗口之上.
        //Android8.0行为变更，对8.0进行适配
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            params1.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            params2.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            params1.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
            params2.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        //params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        //params1.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        //设置效果为背景透明.
        params.format = PixelFormat.RGBA_8888;
        params2.format =params1.format = PixelFormat.RGBA_8888;
        //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
        params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params1.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        params2.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;//|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
        //设置窗口初始停靠位置.
        params.gravity = Gravity.START | Gravity.TOP;
        params2.gravity =params1.gravity = Gravity.START | Gravity.TOP;

        params2.x = 0;
        params2.y = 0;

        if(bCenterMode)
        {
            params.x = screenHeight/2-mSize/2;
            params.y = screenWidth/2 - mSize/2;
        }
        else {
            params.x = screenHeight*3/4;
            params.y = 0;
        }
        //设置悬浮窗口长宽数据.
        params.width = mSize;
        params.height = mSize;

        LayoutInflater inflater = LayoutInflater.from(getApplication());

        //获取浮动窗口视图所在布局.
        toucherLayout = (ConstraintLayout) inflater.inflate(R.layout.float_layout, null);
        toucherLayout1 = (LinearLayout) inflater.inflate(R.layout.quickview_layout, null);
        floatLayout = (AbsoluteLayout) inflater.inflate(R.layout.btn_layout, null);
        //添加toucherlayout
        lv_btnlist = (ListView)toucherLayout1.findViewById(R.id.lv_quick_view);

        iv_btn= new ImageView[mGlobalVar.getDeviceMaxButton()];
        for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
        {
            iv_btn[a] = (ImageView)floatLayout.findViewById(ImgIDTbl[a]);
            ViewGroup.LayoutParams lp = iv_btn[a].getLayoutParams();
            iv_btn[a].setAlpha(((float)mGlobalVar.getPt_Tbl_View_Alpha())/10);
            //Log.d(TAG,"size: "+String.valueOf(lp.width)+" : "+String.valueOf(lp.height)+" : f="+String.valueOf(mGlobalVar.getPt_Tbl_View_Size()));
            lp.width = (int)(lp.width * ((float)(5+mGlobalVar.getPt_Tbl_View_Size())/10));
            lp.height = (int)(lp.height * ((float)(5+mGlobalVar.getPt_Tbl_View_Size())/10));
            mImageHalfSize = lp.height/2 ;//dip2px(this,20);
            //Log.d(TAG,"size: "+String.valueOf(lp.width)+" : "+String.valueOf(lp.height));
        }
        btn_img_pos_reset = (Button) floatLayout.findViewById(R.id.btn_img_pos_reset);
        btn_img_pos_save = (Button) floatLayout.findViewById(R.id.btn_img_pos_save);
        btn_img_pos_exit = (Button) floatLayout.findViewById(R.id.btn_img_pos_exit);
        btn_img_pos_hide = (Button) floatLayout.findViewById(R.id.btn_img_pos_hide);

        //WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            params1.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            params2.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }

        if(mGlobalVar.getFloatMode())
        {
            windowManager.addView(floatLayout, params2);
            bfloatView = true;
        }

        windowManager.addView(toucherLayout, params);


        //Intent intent = new Intent(MainService.this, UserGuideService.class);
        //startService(intent);

        params1.width = qv_ly_width;
        params1.height = qv_ly_height;
        Log.i(TAG, "toucherlayout-->left:" + toucherLayout.getLeft());
        Log.i(TAG, "toucherlayout-->right:" + toucherLayout.getRight());
        Log.i(TAG, "toucherlayout-->top:" + toucherLayout.getTop());
        Log.i(TAG, "toucherlayout-->bottom:" + toucherLayout.getBottom());

        //主动计算出当前View的宽高信息.
        toucherLayout.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        if(mGlobalVar.getIsPortraitGame())
        {
            //用于检测状态栏高度.
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            }
            Log.i(TAG, "状态栏高度为:" + statusBarHeight);
        }

        Configuration mConfiguration = getResources().getConfiguration(); //获取设置的配置信息


        //screenHeight+=statusBarHeight;

        params2.width = screenHeight;
        params2.height = screenWidth;
        Log.i(TAG, "screenHeight:" + screenHeight+" screenWidth:" + screenWidth+" mImageHalfSize:" + mImageHalfSize);

        btn_img_pos_reset.setAlpha(0.9f);
        btn_img_pos_reset.setX(screenHeight/2-dip2px(this,55));
        btn_img_pos_reset.setY(20);
        btn_img_pos_save.setAlpha(0.9f);
        btn_img_pos_save.setX(screenHeight/2+dip2px(this,5));
        btn_img_pos_save.setY(20);
        btn_img_pos_exit.setAlpha(0.9f);
        btn_img_pos_exit.setX(screenHeight/2+dip2px(this,60));
        btn_img_pos_exit.setY(20);
        btn_img_pos_hide.setAlpha(0.9f);
        btn_img_pos_hide.setX(screenHeight/2-dip2px(this,110));
        btn_img_pos_hide.setY(20);
        btn_img_pos_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Log.d(TAG, "Game:" + String.valueOf(mGlobalVar.getmCurGame()));
                AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
                builder.setTitle(getResources().getString(R.string.string_app_update_title))
                        .setMessage(getResources().getString(R.string.string_app_update_message))
                        .setPositiveButton(getResources().getString(R.string.string_app_update_confirm), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                int x, y;
                                if (mGlobalVar.getmCurGame() >= Transfer_Con.MAX_GP_FIX_GAME_NUM) {
                                    mGlobalVar.loadCoordinateTable(mGlobalVar.getmCurPhone(), mGlobalVar.getmCurGame());
                                    pttbl_temp = mGlobalVar.getPTTable();
                                } else {
                                    mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_CLR_POINT_TBL, mGlobalVar.getmCurPhone(), mGlobalVar.getmCurGame());
                                    if (mGlobalVar.get_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 0, u8DataBuffer)) {
                                        short a;
                                        //String str="";
                                        for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                            pttbl_temp[a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                            pttbl_temp[a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                            //str+=String.valueOf(ptTbl[a])+", ";
                                        }
                                        //Log.d(TAG,str);
                                        if (mGlobalVar.get_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton() * 2), (byte) 1, u8DataBuffer)) {
                                            //str="";
                                            for (a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                                pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] = (int) (u8DataBuffer[2 * a + 1] & 0xff) << 8;
                                                pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] += (int) (u8DataBuffer[2 * a] & 0xff);
                                                //str+=String.valueOf(ptTbl[mGlobalVar.getDeviceMaxButton()+a])+", ";
                                            }
                                            mGlobalVar.setPtTbl(pttbl_temp);
                                            //Log.d(TAG,str);
                                        }
                                    }
                                }
                                for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                                    iv_btn[a].setVisibility(View.GONE);
                                    //if((a==Transfer_Con.TI_BUTTON_L_ROCKER)||(a==Transfer_Con.TI_BUTTON_R_ROCKER)||(a==Transfer_Con.TI_BUTTON_SHIFT)||(a==Transfer_Con.TI_BUTTON_LOGO))
                                    //   continue;
                                    y = pttbl_temp[a * 2] * screenWidth / 0x7FFF;
                                    x = pttbl_temp[a * 2 + 1] * screenHeight / 0x7FFF;
                                    iv_btn[a].setX(x - mImageHalfSize);
                                    iv_btn[a].setY(y - mImageHalfSize);
                                    //Log.i(TAG, "iv ; " + String.valueOf(a) + ",l=" + String.valueOf(y) + ",t=" + String.valueOf(x));
                                    if ((pttbl_temp[a * 2] != 0x7fff) || (pttbl_temp[a * 2 + 1] != 0x7fff))
                                        iv_btn[a].setVisibility(View.VISIBLE);
                                }
                                bIsChanged = false;
                            }
                        })
                        .setNegativeButton(getResources().getString(R.string.string_app_update_cancel), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                final AlertDialog dialog = builder.create();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (Settings.canDrawOverlays(MainService.this))
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                }
                else
                {
                    dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                }
                dialog.show();
            }
        });
        btn_img_pos_save.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                mGlobalVar.setPtTbl(pttbl_temp);
                String str="";
                for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++)
                {
                    u8DataBuffer[a*2] = (byte) (pttbl_temp[a]&0xff);
                    u8DataBuffer[a*2+1] = (byte) (pttbl_temp[a]>>8);
                    str += String.valueOf(u8DataBuffer[a*2])+" "+String.valueOf(u8DataBuffer[a*2+1])+", ";
                }
                Log.d(TAG,str);
                str="";
                Log.d(TAG,"pt0:"+String.valueOf(pttbl_temp[0])+"byte:"+String.valueOf(u8DataBuffer[0])+" "+String.valueOf(u8DataBuffer[1]));
                if(mGlobalVar.set_CurPtTbl((byte)(mGlobalVar.getDeviceMaxButton()*2),(byte)0,u8DataBuffer)) {

                    for (int a = 0; a < mGlobalVar.getDeviceMaxButton(); a++) {
                        u8DataBuffer[a * 2] = (byte) (pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] & 0xff);
                        u8DataBuffer[a * 2 + 1] = (byte) (pttbl_temp[mGlobalVar.getDeviceMaxButton() + a] >> 8);
                        str += String.valueOf(u8DataBuffer[a * 2 ])+" "+String.valueOf(u8DataBuffer[a * 2 + 1])+", ";
                    }
                    Log.d(TAG,str);
                    Log.d(TAG,"pt0:"+String.valueOf(pttbl_temp[mGlobalVar.getDeviceMaxButton()])+"byte:"+String.valueOf(u8DataBuffer[0])+" "+String.valueOf(u8DataBuffer[1]));
                    if(mGlobalVar.set_CurPtTbl((byte) (mGlobalVar.getDeviceMaxButton()*2), (byte) 1, u8DataBuffer))
                    {
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SAVE_POINT_TBL,mGlobalVar.getmCurPhone(),mGlobalVar.getmCurGame());
                    }
                }
                mGlobalVar.saveCoordinateTable(mGlobalVar.getmCurPhone(),mGlobalVar.getmCurGame());
                bIsChanged = false;
            }
        });
        btn_img_pos_exit.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(bIsChanged)
                {
                    AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
                    builder.setTitle("提示")
                            .setMessage("您的设置未保存，是否要保存并退出？")
                            .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    btn_img_pos_save.performClick();
                                    //windowManager.removeView(alertDialog);
                                    Intent intent = new Intent();
                                    intent.setClass(getBaseContext(), MainActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getApplication().startActivity(intent);
                                    stopSelf();
                                }
                            })
                            .setNegativeButton("不保存", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //windowManager.removeView(alertDialog);
                                    Intent intent = new Intent();
                                    intent.setClass(getBaseContext(), MainActivity.class);
                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    getApplication().startActivity(intent);
                                    stopSelf();
                                }
                            })
                    .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    final AlertDialog dialog = builder.create();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (Settings.canDrawOverlays(MainService.this))
                            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
                    }
                    else
                    {
                        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    }
                    dialog.show();
                }
                else
                {
                    Intent intent = new Intent();
                    intent.setClass(getBaseContext(), MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getApplication().startActivity(intent);
                    stopSelf();
                }
            }
        });
        btn_img_pos_hide.setOnClickListener(onClickListener);
                //浮动窗口按钮.
        //imageButton1 = (ImageButton) toucherLayout.findViewById(R.id.imageButton1);
        showFloatImage();
        toucherLayout.setOnClickListener(new View.OnClickListener() {
            long[] hints = new long[2];

            @Override
            public void onClick(View v) {
                Log.i(TAG, "点击了");
                System.arraycopy(hints, 1, hints, 0, hints.length - 1);
                hints[hints.length - 1] = SystemClock.uptimeMillis();
                if (SystemClock.uptimeMillis() - hints[0] >= 300) {
                    Log.i(TAG, "要执行");
                    if(mGlobalVar.getFloatMode()) {
                        if(!bfloatView)
                        {
                            windowManager.removeView(toucherLayout);
                            windowManager.addView(floatLayout, params2);
                            windowManager.addView(toucherLayout,params);
                            bfloatView = true;
                        }
                        else
                        {
                            windowManager.removeView(floatLayout);
                            bfloatView = false;
                        }
                    }
                    else if(!bCenterMode){
                        if (!bmenuView) {
                            if (bleftside) {
                                params1.x = params.x + mSize;
                            } else {
                                Log.d(TAG,"toucherLayout1:"+String.format("%d,%d,%d,%d",params1.x,params.x ,mSize,qv_ly_width));
                                params1.x = params.x - mSize - qv_ly_width;
                            }
                            Log.d(TAG,"toucherLayout1a:"+String.format("%d,%d,%d,%d",params1.x,params.x ,mSize,qv_ly_width));
                            params1.y = params.y;
                            windowManager.addView(toucherLayout1, params1);
                            Log.d(TAG,"toucherLayout1 addView");
                            bmenuView = true;
                        } else {
                            windowManager.removeView(toucherLayout1);
                            bmenuView = false;
                        }
                    }
                    Toast.makeText(MainService.this, "连续点击两次以退出", Toast.LENGTH_SHORT).show();
                } else {
                    Log.i(TAG, "即将关闭");
                    stopSelf();
                }
            }
        });

        toucherLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        //lastX = event.getRawX();
                        //lastY = event.getRawY();
                        Log.d(TAG,"x p: "+event.getRawX());
                        Log.d(TAG,"p y: "+event.getRawY());
                        handler.removeMessages(0);
                        if(ENABLE_HALF_HIDE) {
                            if (bHalfshow) {
                                if (bleftside)
                                    toucherLayout.scrollBy(-mSize / 2, 0);
                                else
                                    toucherLayout.scrollBy(mSize / 2, 0);
                                //params.width = 50;
                                windowManager.updateViewLayout(toucherLayout, params);
                                bHalfshow = false;
                            }
                        }

                        break;
                    case MotionEvent.ACTION_MOVE:
                        if(!bCenterMode) {
                            params.x = (int) event.getRawX() - mSize / 2;
                            params.y = (int) event.getRawY() - mSize / 2 - statusBarHeight;
                            windowManager.updateViewLayout(toucherLayout, params);
                            if (bmenuView) {
                                if (params.x < screenWidth / 2)
                                    params1.x = params.x + mSize;
                                else
                                    params1.x = params.x - mSize - qv_ly_width;

                                params1.y = params.y;
                                windowManager.updateViewLayout(toucherLayout1, params1);
                                Log.d(TAG,"toucherLayout1 updateViewLayout");
                            }
                        }
                    break;
                    case MotionEvent.ACTION_UP:
                        if(!bCenterMode) {
                            params.y = (int) event.getRawY() - mSize / 2 - statusBarHeight;
                            if (params.x < screenHeight / 2) {
                                params.x = 0;
                                windowManager.updateViewLayout(toucherLayout, params);
                                bleftside = true;
                            } else {
                                params.x = screenHeight;
                                windowManager.updateViewLayout(toucherLayout, params);
                                bleftside = false;
                            }
                            if (bmenuView) {
                                if (params.x < screenHeight / 2)
                                    params1.x = params.x + mSize;
                                else
                                    params1.x = params.x - mSize - qv_ly_width;

                                params1.y = params.y;
                                windowManager.updateViewLayout(toucherLayout1, params1);
                            }
                            if (!bHalfshow) {
                                {
                                    message = handler.obtainMessage();
                                    message.what = 0;
                                    message.arg1 = (int) params.x;
                                    message.arg2 = (int) params.y;
                                    /*手指抬起5s内没有操作的话，让图标变小*/
                                    handler.sendMessageDelayed(message, 5000);
                                }
                            }
                        }
                        break;
                }
                return false;
            }
        });

        toucherLayout1.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        handler.removeMessages(0);
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:

                        break;
                }
                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) params.x;
                    message.arg2 = (int) params.y;
                    /*手指抬起5s内没有操作的话，让图标变小*/
                    Log.d(TAG,"setOnTouchListener: ");
                    handler.sendMessageDelayed(message, 5000);
                return false;
            }
        });

        if(!bCenterMode) {
            message = handler.obtainMessage();
            message.what = 0;
            message.arg1 = (int) params.x;
            message.arg2 = (int) params.y;
            handler.sendMessageDelayed(message, 5000);
        }
        //******************
        /*
        g_u8tAttrTable[0][0] =0x01;
        g_u8tAttrTable[1][0] =0x01;
        g_u8tAttrTable[2][0] =0x01;
        g_u8tAttrTable[3][0] =0x01;
        g_u8tAttrTable[4][0] =0x01;
        g_u8tAttrTable[5][0] =0x01;
        */
        if(!mGlobalVar.getFloatMode()) {
            listData = new ArrayList<Map<String, Object>>();
            for (int a = 0; a < 3; a++) {
                if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                    for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                        g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];
                    }
                }
            }

            for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {

                if(g_u8tAttrTable[k][0]!=0) {   // have function
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("btn",k );
                    map.put("func",(int)g_u8tAttrTable[k][0] );
                    if ((g_u8tAttrTable[k][0] & 0x80) == 0x80) {    // on
                        map.put("sw",true );
                    } else {
                        map.put("sw",false );
                    }
                    //Log.d(TAG,"attr 0: "+String.format("0x%x",g_u8tAttrTable[k][0] ));
                    listData.add(map);

                }
            }
           // Log.d(TAG,"list size="+String.valueOf(listData.size()));
            funcAdapter = new FuncAdapter(MainService.this);
            lv_btnlist.setAdapter(funcAdapter);
            lv_btnlist.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    switch (scrollState){
                        case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                            message = handler.obtainMessage();
                            message.what = 0;
                            message.arg1 = (int) params.x;
                            message.arg2 = (int) params.y;
                            handler.sendMessageDelayed(message, 5000);
                            break;

                        case SCROLL_STATE_TOUCH_SCROLL:
                            handler.removeMessages(0);
                            Log.d(TAG,"List tv setOnScrollListener: ");
                            break;

                        case SCROLL_STATE_FLING:
                            break;
                    }


                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    //Toast.makeText(MainService.this,""+firstVisibleItem,Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    @Override
    public void onDestroy()
    {
        handler.removeMessages(0);
        unregisterReceiver(broadcastReceive);
        if (toucherLayout != null)
        {
            windowManager.removeView(toucherLayout);
        }
        if((toucherLayout1!=null)&&(bmenuView))
        {
            windowManager.removeView(toucherLayout1);
        }
        if((floatLayout!=null)&&(bfloatView))
        {
            windowManager.removeView(floatLayout);
        }
        Log.d(TAG,"onDestroy");
        super.onDestroy();
    }

    @SuppressLint("ClickableViewAccessibility")
    void showFloatImage()
    {
        {
            int x, y;
            //ViewGroup.LayoutParams para;
            pttbl_temp = mGlobalVar.getPTTable();
            for(int a=0;a<mGlobalVar.getDeviceMaxButton();a++) {
                final int k = a;
                iv_btn[a].setVisibility(View.GONE);
                //if((a==Transfer_Con.TI_BUTTON_L_ROCKER)||(a==Transfer_Con.TI_BUTTON_R_ROCKER)||(a==Transfer_Con.TI_BUTTON_SHIFT)||(a==Transfer_Con.TI_BUTTON_LOGO))
                 //   continue;
                y = pttbl_temp[a*2] * screenWidth / 0x7FFF;
                x = pttbl_temp[a*2+1] * screenHeight / 0x7FFF;
                iv_btn[a].setX(x-mImageHalfSize);
                iv_btn[a].setY(y-mImageHalfSize);
                //Log.i(TAG,"iv ; "+String.valueOf(a)+",l="+String.valueOf(y)+",t="+String.valueOf(x));
                if((pttbl_temp[a*2]!=0x7fff)||(pttbl_temp[a*2+1]!=0x7fff))
                iv_btn[a].setVisibility(View.VISIBLE);

                iv_btn[a].setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        int pos_x,pos_y;
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN:
                                Log.i(TAG,"ACTION_DOWN");
                                break;
                            case MotionEvent.ACTION_MOVE:
                                Log.i(TAG,"ACTION_MOVE");
                                bIsChanged = true;
                                pos_x = (int)event.getRawX()-mImageHalfSize;
                                pos_y = (int)event.getRawY()-mImageHalfSize;
                                v.setX(pos_x);
                                v.setY(pos_y);
                                pttbl_temp[2*k] = (pos_y+mImageHalfSize)*0x7FFF/screenWidth;
                                pttbl_temp[2*k+1] = (pos_x+mImageHalfSize)*0x7FFF/screenHeight;
                                break;
                            case MotionEvent.ACTION_UP:
                                Log.i(TAG,"ACTION_UP");
                                break;
                        }
                        return true;
                    }
                });
            }
        }
    }
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId())
            {
                case R.id.btn_img_pos_hide:
                    if(bfloatView) {
                        windowManager.removeView(floatLayout);
                        btn_img_pos_hide.setText("显示");
                        bfloatView = false;
                    }
                    else
                    {
                        windowManager.addView(floatLayout, params2);
                        btn_img_pos_hide.setText("收起");
                        bfloatView = true;
                    }
                    break;

            }
        }
    };

    class FuncAdapter extends BaseAdapter {
        private Context context = null;

        private FuncAdapter(Context context) {
            this.context = context;
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int position) {
            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            FuncAdapter.ViewHolder mHolder;
            final int pos = position;
            if (convertView == null) {
                mHolder = new FuncAdapter.ViewHolder();
                LayoutInflater inflater = LayoutInflater.from(context);
                convertView = inflater.inflate(R.layout.listview_quick_view, null, true);

                mHolder.iv_lv_btnimg = (ImageView) convertView.findViewById(R.id.iv_qv_btn);
                mHolder.sw_lv_function_onoff = (Switch) convertView.findViewById(R.id.sw_qv_btn);
                mHolder.tv_lv_function = (TextView) convertView.findViewById(R.id.tv_qv_btn);

                convertView.setTag(mHolder);
            } else {
                mHolder = (FuncAdapter.ViewHolder) convertView.getTag();
            }
                mHolder.iv_lv_btnimg.setImageResource(Img[(int)listData.get(position).get("btn")]);
                //Log.d(TAG,"List sw: "+String.valueOf((boolean)listData.get(position).get("sw")));
                mHolder.sw_lv_function_onoff.setChecked((boolean)listData.get(position).get("sw"));
                //Log.d(TAG,"List Btn: "+String.valueOf((int)listData.get(position).get("btn")));
                switch ((int)listData.get(position).get("func")&0x7f)
                {
                    case Transfer_Con.bSkillWithDirect:
                            mHolder.tv_lv_function.setText("施法关联");
                        break;
                    case Transfer_Con.bFPSPullGunDown:
                        mHolder.tv_lv_function.setText("自动压枪");
                        break;
                    case Transfer_Con.ATTR_MACRO:
                        mHolder.tv_lv_function.setText("一键连招");
                        break;
                    case Transfer_Con.bCancelAutoEvent:
                        mHolder.tv_lv_function.setText("取消动作");
                        break;
                        default:
                            mHolder.tv_lv_function.setText("用户定义");
                            break;
                }

            mHolder.tv_lv_function.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    handler.removeMessages(0);
                    message = handler.obtainMessage();
                    message.what = 0;
                    message.arg1 = (int) params.x;
                    message.arg2 = (int) params.y;
                    Log.d(TAG,"List tv setOnClickListener: ");
                    handler.sendMessageDelayed(message, 5000);
                }
            });

                mHolder.sw_lv_function_onoff.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handler.removeMessages(0);
                        final int index = (int)listData.get(pos).get("btn");
                        //mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_AEV_ONOFF,index,0,u8DataBuffer);
                        int data;
                        //Log.d(TAG,"data1: "+String.format("0x%x",data));
                        if(((int)g_u8tAttrTable[index][0]&0x80)==0x80)
                            data = 0;
                        else
                            data = 1;
                        //mGlobalVar.IntToByte((int)data,u8DataBuffer,0);
                        //Log.d(TAG,"data2: "+String.format("0x%x",data));
                        mGlobalVar.tranSet_Value(Transfer_Con.HID_CMD_SET_AEV_ONOFF,data,index);

                        for (int a = 0; a < 3; a++) {
                            if (mGlobalVar.tranGet_Value(Transfer_Con.HID_CMD_GET_KEY_ATTR, a, 0, u8DataBuffer)) {
                                for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {
                                    g_u8tAttrTable[k][a] = u8DataBuffer[16 + k];
                                }
                            }
                        }
                        listData.clear();
                        for (int k = 0; k < mGlobalVar.getDeviceMaxButton(); k++) {

                            if(g_u8tAttrTable[k][0]!=0) {   // have function
                                Map<String, Object> map = new HashMap<String, Object>();
                                map.put("btn",k );
                                map.put("func",(int)g_u8tAttrTable[k][0] );
                                if ((g_u8tAttrTable[k][0] & 0x80) == 0x80) {    // on
                                    map.put("sw",true );
                                } else {
                                    map.put("sw",false );
                                }
                                listData.add(map);
                            }
                        }
                        message = handler.obtainMessage();
                        message.what = 0;
                        message.arg1 = (int) params.x;
                        message.arg2 = (int) params.y;
                        handler.sendMessageDelayed(message, 5000);
                    }

                });
                //Log.d(TAG,"Btn Act: "+mHolder.tv_lv_function.getText());
            return convertView;
                //mHolder.btn_lv_launch.setVisibility(View.VISIBLE);
        }


        class ViewHolder {
            private ImageView iv_lv_btnimg;
            private Switch sw_lv_function_onoff;
            private TextView tv_lv_function;
        }
    }

    class MyBroadcastReceive extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            Configuration mConfiguration = context.getResources().getConfiguration(); //获取设置的配置信息
            int ori = mConfiguration.orientation; //获取屏幕方向
            if (ori == Configuration.ORIENTATION_LANDSCAPE) {
                //横屏
                Log.d(TAG,"横屏 "+String.valueOf(ori));
            } else if (ori == Configuration.ORIENTATION_PORTRAIT) {
                //竖屏
                Log.d(TAG,"竖屏 "+String.valueOf(ori));
                stopSelf();
            }
            String action=intent.getAction();
            if(UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                mGlobalVar.setbIsUsbConnect(false);
                mGlobalVar.setbIsTransferMode(false);
                mGlobalVar.myUsbDevice = null;
                mGlobalVar.myInterface = null;
                mGlobalVar.epOut = null;
                mGlobalVar.epIn = null;
                stopSelf();
                //Toast.makeText(context,"USB Disconnect",Toast.LENGTH_SHORT).show();
                //Log.d("SOE_Rec","USB Disconnect");
            }


         }
    }

}
